package com.cyou.qb.face.util.converter;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;



public class TripleDES 
{    
    public static String faceCipher(byte key[], byte data[],byte[] iv)//加密函数
    {
    	try
    	{
    		
    		IvParameterSpec ivps;
    		ivps = new IvParameterSpec(iv, 0, iv.length);
    		
    		SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede"); //设置密钥工厂模式为DESede，可以设置为AES、DES、DESede、PBEWith等模式    
    		DESedeKeySpec ks = new DESedeKeySpec(key);  //新建密钥规范, 使密钥规范化
    		SecretKey ky2 = kf.generateSecret(ks);  //生成密钥,最后的执行密钥是ky2  

    		Cipher cipher=Cipher.getInstance("DESede/CBC/PKCS5Padding");
    		//打印Cipher对象密码服务提供者信息
    		//加密
    		cipher.init(Cipher.ENCRYPT_MODE,ky2,ivps);//cipher对象初始化，设置为加密
    		byte[] cipherText=cipher.doFinal(data);//结束数据加密，输出密文
    		
    		String re = Base64Coder.encode(cipherText);
    		
    		
    		
//    		cipherTextdes=cipherText;//把密文赋给全局的密文变量
//    		//HexcipherText1=byte2HexStr(cipherTextdes);
//    		HexcipherText=Base64Coder.encode(cipherTextdes);
    		
    		return re;//返回密文,返回的是字符串型的密文
    	
    	}
    	catch (Exception e)
    	{
    		return null;
    	}
    }
    
    public static byte[]  test_Decrypt(byte key[], String datades,byte[] iv)//解密函数，要输入的密文要求为字符串形式
    {   
    	byte[] newPlainText;
    	byte[] data;
		try 
		{   
			
			data=Base64Coder.decode(datades);
			IvParameterSpec ivps;
    		ivps = new IvParameterSpec(iv, 0, iv.length);
			KeySpec ks = new DESedeKeySpec(key);     
	        SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede");     
	        SecretKey ky = kf.generateSecret(ks);     
	        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");     
	        cipher.init(Cipher.DECRYPT_MODE, ky,ivps);     
	            //输出原文
			newPlainText = cipher.doFinal(data);//这里在放入android时请去掉
	    	
	    	return newPlainText;//返回明文
		} 
		catch (Exception e) 
		{
			return null;
		} 
		
   }

}
    

